package com.jjy.boot.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jjy.boot.common.Result;
import com.jjy.boot.entity.User;
import com.jjy.boot.mapper.UserMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController //定义返回json数据
@RequestMapping("/user") //定义路由
public class UserController {

//    该做法不规范
    @Resource //将mapper引入到controller中
        UserMapper userMapper;

//    登录
    @PostMapping("/login") //定义post接口
    public Result<?> login(@RequestBody User user){ //@RequestBody 将传来的json数据转换为java对象
        //sql查询
        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()).eq(User::getPassword, user.getPassword()));
        if(res == null){
            return Result.error("-1","用户名或密码错误");
        }
        return Result.success();
    }

//    登录
    @PostMapping("/register") //定义post接口
    public Result<?> register(@RequestBody User user){ //@RequestBody 将传来的json数据转换为java对象
        //sql查询
        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));
        if(res != null){
            return Result.error("-1","用户名重复");
        }
        if(user.getPassword() == null){
//            设置默认密码
            user.setPassword("123456");
        }
        userMapper.insert(user);
        return Result.success();
    }

//    添加
    @PostMapping //定义post接口
    public Result<?> save(@RequestBody User user){ //@RequestBody 将传来的json数据转换为java对象
        if(user.getPassword() == null){
            user.setPassword("123456");
        }
        userMapper.insert(user);
        return Result.success();
    }

//    更新
    @PutMapping //定义put接口
    public Result<?> update(@RequestBody User user) {
        userMapper.updateById(user);
        return Result.success();
    }

//    删除
    @DeleteMapping("/{id}") //定义delete接口
    public Result<?> update(@PathVariable Long id) {
        userMapper.deleteById(id);
        return Result.success();
    }


//    获取
    @GetMapping //定义get接口
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search){ //@RequestBody 将传来的json数据转换为java对象
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery();
        if(StrUtil.isNotBlank(search)){
            wrapper.like(User::getNickName, search);
        }
        Page<User> userPage = userMapper.selectPage(new Page<>(pageNum,pageSize), wrapper);
        return Result.success(userPage);
    }

}
